package com.ruoyix.flowable.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyix.common.utils.JsonUtils;
import com.ruoyix.common.utils.StringUtils;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.Model;
import org.flowable.engine.repository.ModelQuery;
import org.springframework.stereotype.Service;
import com.ruoyix.flowable.domain.bo.BpmModelBo;
import com.ruoyix.flowable.domain.vo.BpmModelVo;
import com.ruoyix.flowable.domain.BpmModel;
import com.ruoyix.flowable.mapper.BpmModelMapper;
import com.ruoyix.flowable.service.IBpmModelService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 模型管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-20
 */
@RequiredArgsConstructor
@Service
public class BpmModelServiceImpl implements IBpmModelService {

    private final BpmModelMapper baseMapper;

    private final RepositoryService repositoryService;

    /**
     * 查询模型管理
     */
    @Override
    public BpmModelVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询模型管理列表
     */
    @Override
    public TableDataInfo<BpmModelVo> queryPageList(BpmModelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BpmModel> lqw = buildQueryWrapper(bo);
        Page<BpmModelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

//        ModelQuery query = repositoryService.createModelQuery();
//        if (org.apache.commons.lang3.StringUtils.isNotEmpty(bo.getModelName())) {
//            query.modelNameLike("%" + bo.getModelName() + "%");
//        }
//        if (org.apache.commons.lang3.StringUtils.isNotEmpty(bo.getModelKey())) {
//            query.modelKey(bo.getModelKey());
//        }
//        query.orderByLastUpdateTime().desc();
//        //创建时间降序排列
//        query.orderByCreateTime().desc();
//        // 分页查询
//        List<Model> modelList = query.listPage((pageQuery.getPageNum()-1)* pageQuery.getPageSize(), pageQuery.getPageNum()* pageQuery.getPageSize());


        return TableDataInfo.build(result);
    }

    /**
     * 查询模型管理列表
     */
    @Override
    public List<BpmModelVo> queryList(BpmModelBo bo) {
        LambdaQueryWrapper<BpmModel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BpmModel> buildQueryWrapper(BpmModelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BpmModel> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getModelId()), BpmModel::getModelId, bo.getModelId());
        lqw.like(StringUtils.isNotBlank(bo.getModelName()), BpmModel::getModelName, bo.getModelName());
        lqw.eq(StringUtils.isNotBlank(bo.getModelKey()), BpmModel::getModelKey, bo.getModelKey());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), BpmModel::getCategory, bo.getCategory());
        return lqw;
    }

    /**
     * 新增模型管理
     */
    @Override
    public Boolean insertByBo(BpmModelBo bo) {
        BpmModel add = BeanUtil.toBean(bo, BpmModel.class);
        validEntityBeforeSave(add);
        Model model = repositoryService.newModel();
        model.setName(bo.getModelName());
        model.setKey(bo.getModelKey());
        model.setCategory(bo.getCategory());
        model.setMetaInfo(JsonUtils.toJsonString(bo));
        // 保存流程模型
        repositoryService.saveModel(model);
        add.setModelId(model.getId());
        add.setVersion(Long.valueOf(model.getVersion()));
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模型管理
     */
    @Override
    public Boolean updateByBo(BpmModelBo bo) {
        BpmModel update = BeanUtil.toBean(bo, BpmModel.class);
        validEntityBeforeSave(update);

        Model model = repositoryService.getModel(bo.getModelId());
        if(ObjectUtil.isEmpty(model)){
            throw  new RuntimeException("流程模型不存在");
        }

        model.setName(bo.getModelName());
        model.setKey(bo.getModelKey());
        model.setCategory(bo.getCategory());
        model.setMetaInfo(JsonUtils.toJsonString(bo));
        model.setVersion(model.getVersion()+1);
        model.setMetaInfo(null);
        // 保存流程模型
        repositoryService.saveModel(model);
        //保存xml文件
        repositoryService.addModelEditorSource(model.getId(), StrUtil.utf8Bytes(bo.getBpmnXml()));
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BpmModel entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除模型管理
     */
    @Override
    //TODO 流程删除逻辑后续开发
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 流程部署
     * @param modelId
     * @return
     */
    @Override
    public Boolean deploy(String modelId) {

        //检测流程模型是否存在
        Model model = repositoryService.getModel(modelId);
        if(ObjectUtil.isEmpty(model)){
            throw new RuntimeException("流程模型不存在");
        }

        //检测流程模型设计图是否存在
        byte[] xmlBytes = repositoryService.getModelEditorSource(modelId);
        if (xmlBytes == null) {
            throw new RuntimeException("流程模型设计不存在，请先设计流程模型后部署");
        }

        //流程部署
        String processName = model.getName() + ".bpmn";
        Deployment deployment = repositoryService.createDeployment()
            // 部署名称
            .name(model.getName())
            // 部署标识key
            .key(model.getKey())
            // bpmn.xml资源
            .addBytes(processName, xmlBytes)
            .deploy();


        //todo 设置 ProcessDefinition 的 category 分类
//            ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
//                .deploymentId(deployment.getId()).singleResult();
//            repositoryService.setProcessDefinitionCategory(definition.getId(), "createReqDTO.getCategory()");

        model.setDeploymentId(deployment.getId());
        repositoryService.saveModel(model);
        return true;
    }
}
